import { validateMobile } from '@/libs/validate';

export default {
  name: 'login',
  components: {},
  data() {
    return {
      loginByPassword: true, // 密码
      form: {
        phone: '',
        code: '',
        password: '',
      },
      countdown: -1,
      user: this.$storage.get('user'),
      appName: this.$storage.get('appName') || 'MoreGold',
    };
  },
  computed: {
    disabledSubmit() {
      const { loginByPassword, form: { phone, code, password } } = this;
      return !phone || (loginByPassword ? !password : !code);
    },
  },
  methods: {
    onSubmit() {
      if (this.disabledSubmit) return;
      // 登录
      const { phone, code, password } = this.form;

      if (!validateMobile(phone)) {
        this.$toast('Please input correct cellphone number'); // Please input correct cellphone number
        return;
      }

      const params = {
        phone,
        // validCode: code,
        // password,
        product: this.appName,
      };

      if (this.loginByPassword) {
        if (!/^.{6,20}$/.test(password)) {
          // Please enter 6-20 digit alphanumeric password combination
          this.$toast('Please enter 6-20 digit alphanumeric password combination');
          return;
        }
        params.password = password;
      } else {
        if (!/^.{4,10}$/.test(code)) {
          this.$toast('Valid Code Error');
          return;
        }
        params.validCode = code;
      }

      this.$api.user.login(params).then(res => {
        const { status, data } = res;
        if ('1' === status) {
          this.$storage.set('user', data);
          this.user = data;
          // 通知APP
        }
      });
    },
    getMsgCode() {
      const { phone } = this.form;

      if (!validateMobile(phone)) {
        this.$toast('Please input correct cellphone number');
        return;
      }

      // 短信类型: LOAN_CODE 借款验证短信; LOGIN_CODE 登录/注册验证短信; UPDATE_PASSWORD_CODE修改密码短信；REPAYMENT_CONFIRM 用户还款确认; DELAY_CODE 展期支付验证码短信
      const params = {
        phone,
        smsType: 'LOGIN_CODE',
        product: this.appName,
      };
      this.$api.user.getCode(params).then(res => {
        const { status, data } = res;
        if ('1' === status) {
          this.countdown = +data.sleep;
          setInterval(() => {
            if (this.countdown > 0) {
              this.countdown--;
            }
          }, 1000);
        }
      });
    },
  },
  created() {
  },
};
